<template>
  <div class="region-menu">
    <select v-model="selectedAreaName" @change="handleChange">
      <option v-if="selectedAreas.length > 0" disabled>
        已选区域: {{ selectedAreas.join(' > ') }}
      </option>
      <option v-if="currentLevel > 1" value="back">返回上一级</option>
      <option v-for="area in currentLevelAreas" :key="area.id" :value="area.name">
        {{ area.name }}
      </option>
    </select>
  </div>
</template>

<script setup>
import { ref, watch, computed, defineEmits } from 'vue';
import { areaDataService } from '@/services';

const selectedAreaName = ref('');
const areas = ref([]);
const currentLevel = ref(1);
const pathStack = ref([]);
const selectedAreas = ref([]);
const emit = defineEmits(['areaClicked']);

const getAreas = async () => {
  try {
    const areaData = (await areaDataService.getRegionService(1)).data;
    areas.value = areaData;
    updateCurrentLevelAreas();
  } catch (error) {
    console.error('Error fetching area data:', error);
  }
};

const updateCurrentLevelAreas = () => {
  const currentPath = pathStack.value.join(' | ');
  return areas.value.filter(area => {
    if (currentLevel.value === 1) {
      return area.level === currentLevel.value;
    } else {
      return area.path.startsWith(currentPath) && area.level === currentLevel.value;
    }
  });
};

const currentLevelAreas = computed(updateCurrentLevelAreas);

const handleChange = () => {
  if (selectedAreaName.value === 'back') {
    goBack();
  } else {
    const selected = areas.value.find(area => area.name === selectedAreaName.value);
    if (selected) {
      pathStack.value.push(selected.name);
      selectedAreas.value.push(selected.name);
      currentLevel.value++;
      selectedAreaName.value = selected.name;
      if (currentLevel.value > 3) {
        emit('areaClicked', selected.id);
      }
      getAreas();
    }
  }
};

const goBack = () => {
  if (currentLevel.value > 1) {
    pathStack.value.pop();
    selectedAreas.value.pop();
    currentLevel.value--;
    selectedAreaName.value = '';
    getAreas();
  }
};

watch(currentLevel, updateCurrentLevelAreas);

getAreas();
</script>

<style scoped>
.region-menu {
  background-color: #2b2b2b;
  color: #ffffff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 10px;
  width: 100%;
}

select {
  width: 100%;
  padding: 10px;
  border: 1px solid #555555;
  border-radius: 4px;
  background-color: #333333;
  color: #ffffff;
}

option {
  background-color: #333333;
  color: #ffffff;
}

option[disabled] {
  font-weight: bold;
  color: #ffdd57;
}

button {
  padding: 10px;
  background-color: #1a1a1a;
  color: #ffffff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #333333;
}
</style>
